package com.shanzmoo.pay.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shanzmoo.db.module.integral.entity.IntegralOrderEntity;
import com.shanzmoo.db.module.merchant.entity.MerchantOrderEntity;
import com.shanzmoo.db.module.pay.entity.SPayOrderInfoEntity;
import com.shanzmoo.db.module.pay.service.ISPayOrderInfoService;
import com.shanzmoo.pay.domain.request.payRequest.SaobeiJsPayRequest;
import com.shanzmoo.pay.domain.request.payRequest.SaobeiOrderQueryRequest;
import com.shanzmoo.pay.domain.response.payResponse.SaobeiJsPayResponse;
import com.shanzmoo.pay.domain.response.payResponse.SaobeiOrderQueryResponse;
import com.shanzmoo.pay.util.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * @author dingmeng
 * @title: PayManager
 * @projectName jyf-mall-server
 * @description: 扫呗--支付模块
 * @date 2021/4/415:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SaobeiPayManager {
    @Value("${wx.mp.appId}")
    private String appId;
    @Value("${saobei.payVer}")
    private String payVer;
    @Value("${saobei.pay.notifyUrl}")
    private String notifyUrl;
    private final ISPayOrderInfoService iSPayOrderInfoService;

    public SaobeiJsPayRequest createPayRequest(MerchantOrderEntity orderEntity, String openId) {
        SaobeiJsPayRequest request = new SaobeiJsPayRequest();
        request.setTerminal_trace(orderEntity.getTerminalRecordNo());
        request.setTerminal_time(DateUtil.now());
        request.setTotal_fee(orderEntity.getAmount().toString());
        request.setOrder_body(orderEntity.getRemark());
        request.setOpen_id(openId);
        request.setSub_appid(appId);
        request.setPay_ver("");
        request.setPay_type(orderEntity.getPayType());
        request.setService_id("012");
        request.setMerchant_no(orderEntity.getMerchantCode());
        request.setTerminal_id(orderEntity.getTerminalNo());
        return request;
    }
    /**
     *
     * @param orderEntity 权益订单
     * @param openId 公众号id
     * @param accessToken 支付令牌
     * @return
     */
    @SneakyThrows
    public SaobeiJsPayResponse addPayOrder(IntegralOrderEntity orderEntity, String openId, String accessToken,String payType) {
        SPayOrderInfoEntity orderInfo = new SPayOrderInfoEntity();
        orderInfo.setOrderCode(orderEntity.getOrderNo());
        orderInfo.setOrderType(Constants.ORDER_TYPE_SCAN);
        orderInfo.setPayOrderCode(RandomUtils.getRandom(32));
        orderInfo.setMerchantNo("");
        orderInfo.setTerminalId("");
        orderInfo.setTerminalTime(DateUtil.format(LocalDateTime.now(),"yyyyMMddHHmmss"));
        orderInfo.setPayType(payType);
        orderInfo.setTotalFee(orderEntity.getOrderPrice().toString());
        //微信支付
        if (StrUtil.equals(payType,Constants.PAY_TYPE_WEIXIN)) {
            orderInfo.setOpenId(openId);
            orderInfo.setAppId(appId);
        }
        //支付宝支付
        if (StrUtil.equals(payType,Constants.PAY_TYPE_ALIPAY)) {
            orderInfo.setUserId(openId);
        }
        orderInfo.setOrderBody(orderEntity.getRemark());
        //未支付
        orderInfo.setPayStatus(Constants.ORDER_STATUS_UNPAID);
        SaobeiJsPayResponse response = jspay(orderInfo,accessToken);
        //预支付请求成功
        if (response.getReturn_code().equals(Constants.RESULT_CODE_SUCCESS)) {
            orderInfo.setOutTradeNo(response.getOut_trade_no());
            orderInfo.setTimeStamp(response.getTimeStamp());
            orderInfo.setNonceStr(response.getNonceStr());
            orderInfo.setPackageStr(response.getPackage_str());
            orderInfo.setSignType(response.getSignType());
            orderInfo.setPaySign(response.getPaySign());
            orderInfo.setAliTradeNo(response.getAli_trade_no());
        }
        Assert.isTrue(iSPayOrderInfoService.save(orderInfo),"支付订单订单创建失败");
        return response;
    }

    /**
     *
     * @param orderEntity 业务订单
     * @param openId 公众号id
     * @param accessToken 支付令牌
     * @return
     */
    @SneakyThrows
    public SaobeiJsPayResponse addPayOrder(MerchantOrderEntity orderEntity, String openId,String accessToken) {
        SPayOrderInfoEntity orderInfo = new SPayOrderInfoEntity();
        orderInfo.setOrderCode(orderEntity.getTerminalRecordNo());
        orderInfo.setOrderType(Constants.ORDER_TYPE_SCAN);
        orderInfo.setPayOrderCode(RandomUtils.getRandom(32));
        orderInfo.setMerchantNo(orderEntity.getMerchantCode());
        orderInfo.setTerminalId(orderEntity.getTerminalNo());
        orderInfo.setTerminalTime(DateUtil.format(LocalDateTime.now(),"yyyyMMddHHmmss"));
        orderInfo.setPayType(orderEntity.getPayType());
        orderInfo.setTotalFee(orderEntity.getAmount().toString());
        //微信支付
        if (orderEntity.getPayType().equals(Constants.PAY_TYPE_WEIXIN)) {
            orderInfo.setOpenId(openId);
            orderInfo.setAppId(appId);
        }
        //支付宝支付
        if (orderEntity.getPayType().equals(Constants.PAY_TYPE_ALIPAY)) {
            orderInfo.setUserId(openId);
        }
        orderInfo.setOrderBody(orderEntity.getRemark());
        //未支付
        orderInfo.setPayStatus(Constants.ORDER_STATUS_UNPAID);
        SaobeiJsPayResponse response = jspay(orderInfo,accessToken);
        //预支付请求成功
        if (response.getReturn_code().equals(Constants.RESULT_CODE_SUCCESS)) {
            orderInfo.setOutTradeNo(response.getOut_trade_no());
            orderInfo.setTimeStamp(response.getTimeStamp());
            orderInfo.setNonceStr(response.getNonceStr());
            orderInfo.setPackageStr(response.getPackage_str());
            orderInfo.setSignType(response.getSignType());
            orderInfo.setPaySign(response.getPaySign());
            orderInfo.setAliTradeNo(response.getAli_trade_no());
        }
        Assert.isTrue(iSPayOrderInfoService.save(orderInfo),"支付订单订单创建失败");
        return response;
    }

    /**
     * 公众号预支付
     *
     * @param orderInfo
     * @throws Exception
     */
    @SneakyThrows
    public SaobeiJsPayResponse jspay(SPayOrderInfoEntity orderInfo, String accessToken) {
        SaobeiJsPayRequest requst = new SaobeiJsPayRequest();
        requst.setPay_ver(payVer);
        requst.setPay_type(orderInfo.getPayType());
        requst.setService_id("012");
        requst.setMerchant_no(orderInfo.getMerchantNo());
        requst.setTerminal_id(orderInfo.getTerminalId());
        requst.setTerminal_trace(orderInfo.getPayOrderCode());
        requst.setTerminal_time(orderInfo.getTerminalTime());
        requst.setTotal_fee(orderInfo.getTotalFee());
        if (orderInfo.getPayType().equals(Constants.PAY_TYPE_WEIXIN)) {
            requst.setSub_appid(appId);
            requst.setOpen_id(orderInfo.getOpenId());
        }
        if (orderInfo.getPayType().equals(Constants.PAY_TYPE_ALIPAY)) {
            requst.setOpen_id(orderInfo.getUserId());
        }
        requst.setOrder_body(orderInfo.getOrderBody());
        requst.setNotify_url(notifyUrl);
        //发送请求
        log.info("公众号预支付请求报文:" + JSON.toJSONString(requst));
        JSONObject obj = ApiUtil.convertRequest(requst, accessToken, "access_token");
        String xmlText = HttpClientUtils.post(ApiConstants.service_url_pay + "/pay/110/jspay", obj.toJSONString());
        SaobeiJsPayResponse response = JSON.parseObject(xmlText, SaobeiJsPayResponse.class);
        log.info("公众号预支付返回报文:" + JSON.toJSONString(response));
        return response;
    }

    /**
     * 支付订单查询
     * @param requst
     * @param accessToken
     * @return
     */
    @SneakyThrows
    public SaobeiOrderQueryResponse queryPayOrder(SaobeiOrderQueryRequest requst, String accessToken) {
        requst.setPay_ver(payVer);
        //自动识别支付类型
        requst.setPay_type("000");
        requst.setService_id("012");
        //发送请求
        log.info("支付订单查询请求报文:" + JSON.toJSONString(requst));
        JSONObject obj = ApiUtil.convertRequest(requst, accessToken, "access_token");
        String xmlText = HttpClientUtils.post(ApiConstants.service_url_pay + "/pay/110/query", obj.toJSONString());
        SaobeiOrderQueryResponse response = JSON.parseObject(xmlText, SaobeiOrderQueryResponse.class);
        log.info("支付订单查询返回报文:" + JSON.toJSONString(response));
        return response;
    }

    public static void main(String[] args) throws Exception {
        //创建公众号预支付requst
//        SPayOrderInfoEntity orderInfo = new SPayOrderInfoEntity();
//        orderInfo.setPayType("010");
//        orderInfo.setMerchantNo(ApiConstants.MERCHANT_NO);
//        orderInfo.setTerminalId("12535186");
//        orderInfo.setPayOrderCode("73396424131077679096845769849635");
//        orderInfo.setTerminalTime(DateUtil.format(LocalDateTime.now(),"yyyyMMddHHmmss"));
//        orderInfo.setTotalFee("1");
//        orderInfo.setOpenId("odEwj6mw4nvxymxCy8Q56fw_dnHA");
////        orderInfo.setUserId("2088912310322292");
//        orderInfo.setOrderBody("支付测试");
//        jspay(orderInfo,"8d677867561140f487507d3145769d64");
//        //创建支付订单查询requst
//        SaobeiOrderQueryRequest requst = new SaobeiOrderQueryRequest();
//        requst.setMerchant_no(ApiConstants.MERCHANT_NO);
//        requst.setTerminal_id("12535186");
//        requst.setTerminal_trace(RandomUtils.getRandom(32));
//        requst.setTerminal_time(DateUtil.format(LocalDateTime.now(),"yyyyMMddHHmmss"));
//        requst.setOut_trade_no("125351866821321042323164701786");
//        queryPayOrder(requst,"8d677867561140f487507d3145769d64");
    }

}
